import { reqGetInfo, reqGetInfoById, reqLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(), // token字符串
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  removeToken() {
    // 清除vuex中的token
    state.token = ''
    // 清除本地
    removeToken()
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo() {
    state.userInfo = {}
  }
}
const actions = {
  async login(ctx, data) {
    const res = await reqLogin(data)
    const token = res.data
    console.log(token)
    ctx.commit('setToken', token)
    return res
  },
  async getUserInfo(context) {
    const { data: data1 } = await reqGetInfo()
    const { data: data2 } = await reqGetInfoById(data1.userId)
    console.log('id', data2)
    const result = {
      ...data1,
      ...data2
    }
    context.commit('setUserInfo', result)
    return result
  },
  async logout(context) {
    // 清除vuex中的token和本地的token
    context.commit('removeToken')
    // 清除用户信息
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
